package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.OrderDetail;
import com.itheima.reggie.domain.Orders;
import com.itheima.reggie.domain.ShoppingCart;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /*****
     * 订单分页查询
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page<OrdersDto>> page(int page, int pageSize, String number, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        log.info("传来的订单数据是:{},{},{},{} ", page, pageSize, beginTime, endTime);
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();

        lqw.like(StringUtils.isNotEmpty(number), Orders::getNumber, number);
        lqw.between(beginTime != null && endTime != null, Orders::getOrderTime, beginTime, endTime);

        orderService.page(ordersPage, lqw);

        //拷贝
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");

        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> ordersDtos = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            //查询用户信息
            Long userId = orders.getUserId();
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>();
            userLambdaQueryWrapper.eq(userId != null, User::getId, userId);
            User user = userService.getOne(userLambdaQueryWrapper);
            //赋值
            ordersDto.setUserName(user.getName());
            ordersDto.setPhone(user.getPhone());

            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }


    /***
     * 查询最新的订单信息
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> get(int page, int pageSize) {
        //分页构造器
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime);
        Page<Orders> ordersP = orderService.page(ordersPage, lqw);

        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(ordersP, ordersDtoPage, "records");

        List<Orders> ordersList = ordersP.getRecords();
        List<OrdersDto> ordersDtoList = ordersList.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            LambdaQueryWrapper<OrderDetail> orderDetailLqw = new LambdaQueryWrapper<>();
            orderDetailLqw.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> list = orderDetailService.list(orderDetailLqw);
            ordersDto.setOrderDetails(list);
            //查询当前用户
            User user = userService.getById(BaseContext.getCurrentId());
            ordersDto.setUserName(user.getName());
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(ordersDtoList);
        return R.success(ordersDtoPage);
    }

    /****
     * 下单方法
     * @param session
     * @return
     */
    @PostMapping("/submit")
    public R<String> order(HttpSession session) {
        Orders orders = (Orders) session.getAttribute("orders");
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /***
     * 修改订单状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders orders) {
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(orders.getId() != null, Orders::getId, orders.getId());
        updateWrapper.set(Orders::getStatus, orders.getStatus());
        orderService.update(updateWrapper);
        return R.success("状态修改成功");
    }

    /***
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<List<OrderDetail>> again(@RequestBody Orders orders) {
        //1.获取当前传来的订单id
        Long ordersId = orders.getId();
        //2.根据订单id去查询订单明细 ,菜品 和 数量
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ordersId != null, OrderDetail::getOrderId, ordersId);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);

        //3.再添加到购物车中去
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartService.saveBatch(shoppingCartList);
        return R.success(orderDetailList);
    }

    @GetMapping("/count")
    public R<List<Map>> count(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
                                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {

     List<Map> list = orderService.reportConut(startTime,endTime);
     return R.success(list);
     /*   QueryWrapper<OrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("dish_id");
        queryWrapper.select("name", "count(*) as count").groupBy("name");
        queryWrapper.orderByDesc("count(*)");
        queryWrapper.last("limit 0,8");
        //queryWrapper.between(beginTime != null && endTime != null ,OrderDetail::g)
        List<Map<String, Object>> maps = orderDetailService.listMaps(queryWrapper);
        return R.success(maps);*/
    }

}
